package Node

import (
	"fmt"
	"os"
	"os/exec"
)


// 前台启动 node app
func NodeCommand(GoBoxPath, BotPath, NodePath, FFmpegPath string) error {
    os.Chdir(GoBoxPath)
    if err := os.Chdir(BotPath); err != nil {
        //红色字体
        fmt.Println("\033[31m Error：切换目录失败", err, "\033[0m")
    }
    fmt.Println("当前目录为:", BotPath)
    cmd := exec.Command("bash", "-c", "node app")
	cmd.Env = []string{
		fmt.Sprintf("NODE_HOME=%s", NodePath),
		fmt.Sprintf("FFMPEG_HOME=%s", FFmpegPath),
		fmt.Sprintf("PATH=%s", os.Getenv("PATH")),
	}
	//测试Env
	fmt.Println(cmd.Env)
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Start(); err != nil {
        return err
    }
    if err := cmd.Wait(); err != nil {
        return err
    }
    return nil
}

// 使用 pnpm 启动、停止、重启或查看日志
func PnPmCommand(GoBoxPath, BotPath, NodePath, FFmpegPath string, order int) error {
    os.Chdir(GoBoxPath)
    if err := os.Chdir(BotPath); err != nil {
        //红色字体
        fmt.Println("\033[31m Error：切换目录失败", err, "\033[0m")
    }
    var cmd *exec.Cmd

    switch order {
    case 1:
        cmd = exec.Command("pnpm", "start")
    case 2:
        cmd = exec.Command("pnpm", "stop")
    case 3:
        cmd = exec.Command("pnpm", "restart")
    case 4:
        cmd = exec.Command("pnpm", "run", "log")
    }
    
    cmd.Env = []string{
        fmt.Sprintf("NODE_HOME=%s", NodePath),
        fmt.Sprintf("FFMPEG_HOME=%s", FFmpegPath),
        fmt.Sprintf("PATH=%s", os.Getenv("PATH")),
    }
    
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    
    if err := cmd.Start(); err != nil {
        return err
    }
    
    if err := cmd.Wait(); err != nil {
        return err
    }
    
    //没有报错则输出操作成功
    fmt.Println("\033[32m Success：操作成功\033[0m")
    //回到GoBox目录
    if err := os.Chdir(GoBoxPath); err != nil {
        //红色字体
        fmt.Println("\033[31m Error：切换GoBox目录失败", err, "\033[0m")
    }
    return nil
}